﻿using AutoCommunication.Base;
using AutoCommunication.Clients;
using AutoCommunication.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace AutoCommunication
{
    /// <summary>
    ///
    /// </summary>
    public partial class Auto
    {
        /// <summary>
        /// 系统运行状态,目前逻辑不严谨,没有经过测试
        /// </summary>
        public static bool Status { get; set; } = false;
        /// <summary>
        /// 运行实例
        /// </summary>
        public static List<IDevice> Devices { get; set; }
        /// <summary>
        /// 用于配置
        /// </summary>
        public static List<IDevice> DevicesConfig { get; set; }
        /// <summary>
        /// 当前系统所有的变量
        /// <para>key:设备名_变量名</para>
        /// <para>value:变量</para>
        /// </summary>
        public static Dictionary<string, BaseVariable> AllVarable { get; set; } = new Dictionary<string, BaseVariable>();

        /// <summary>
        /// 所有的设备集合
        /// <para>key:设备名</para>
        /// <para>value:设备</para>
        /// </summary>
        public static ObservableCollection<IDevice2> AllDevice { get; set; } = new ObservableCollection<IDevice2>();

        ///// <summary>
        ///// 所有变量的当前值:预防直接访问TotalVarableList,可能会有线程安全的问题
        ///// 1.比AllVarable轻便，以后看能否用上
        ///// </summary>
        //public static Dictionary<string, string> CurrentValueList { get; set; } = new Dictionary<string, string>();

        /// <summary>
        /// 根据配置文件启动
        /// </summary>
        /// <param name="path">启动配置文件路径，默认setting.json</param>
        /// <param name="logger"></param>
        /// <param name="alarmer"></param>
        /// <param name="dataChange"></param>
        /// <returns></returns>
        public static Result StartAllDeviceByJson(string path = "setting.json", LoggerDelegate logger = null, Action<BaseVariable, AlarmEventArgs> alarmer = null, Action<BaseVariable> dataChange = null)
        {
            Result result = new Result();
            if (result.SetErrInfo(StopAllDevice()).IsSucceed)
            {
                var res = LoadByJson();
                result.SetErrInfo(res);
                if (res.IsSucceed)
                {
                    //  AllDevice = res.Value;
                    foreach (var dev in res.Value)
                    {
                        result.SetErrInfo(dev.Start(logger, alarmer, dataChange));
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 停止所有的设备
        /// </summary>
        /// <returns></returns>
        public static Result StopAllDevice()
        {
            Result result = new Result();
            foreach (var dev in Auto.AllDevice)
            {
                result.SetErrInfo(dev.Stop());
            }
            return result;
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public static Result<ObservableCollection<IDevice2>> LoadByJson(string path = "setting.json")
        {
            Result<ObservableCollection<IDevice2>> result = new Result<ObservableCollection<IDevice2>>();
            try
            {
                var str = File.ReadAllText(path);
                var res = JsonConvert.DeserializeObject<ObservableCollection<IDevice2>>(str, new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.Auto,
                    Converters = new List<JsonConverter>() { new StringEnumConverter() },
                    Formatting = Formatting.Indented
                });
                result.Value = res;
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                return result;
            }
            return result;
        }
    }
}